import mysql from 'mysql2/promise';
import pg from 'pg';
import { logger } from '../utils/logger.js';
import { DatabaseType as DBType } from '../types/index.js';
import { config } from './env.js';

const { Pool: PgPool } = pg;

// 当前选择的数据库类型
const dbType = config.db.type;

// 创建连接池
const mysqlPool = dbType === DBType.MYSQL ? mysql.createPool(config.db.mysql) : undefined;
const postgresPool = dbType === DBType.POSTGRES ? new PgPool(config.db.postgres) : undefined;

// 获取当前配置的数据库连接池
function getDbPool(): mysql.Pool | pg.Pool {
  if (dbType === DBType.MYSQL && mysqlPool) {
    return mysqlPool;
  } else if (dbType === DBType.POSTGRES && postgresPool) {
    return postgresPool;
  }
  throw new Error(`未配置有效的数据库连接: ${dbType}`);
}

// 测试连接
async function testConnections(): Promise<void> {
  try {
    if (dbType === DBType.MYSQL && mysqlPool) {
      // 测试 MySQL 连接
      const [result] = await mysqlPool.query<mysql.RowDataPacket[]>('SELECT 1');
      logger.info('MySQL 连接成功', { result });
    } else if (dbType === DBType.POSTGRES && postgresPool) {
      // 测试 PostgreSQL 连接
      const pgResult = await postgresPool.query('SELECT 1');
      logger.info('PostgreSQL 连接成功', { rows: pgResult.rows });
    } else {
      throw new Error(`未配置数据库连接: ${dbType}`);
    }
  } catch (error) {
    if (error instanceof Error) {
      logger.error('数据库连接测试失败', {
        message: error.message,
        stack: error.stack,
        type: error.name,
      });
    } else {
      logger.error('数据库连接测试失败', { error });
    }
    throw error;
  }
}

export { mysqlPool, postgresPool, getDbPool, dbType, testConnections };
